package com.ruoyi.api.customer;

import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.system.domain.CCustomerLabel;
import com.ruoyi.system.domain.CrmUser;
import com.ruoyi.system.domain.CrmJob;
import com.ruoyi.system.domain.dto.LitterBsCityDTO;
import com.ruoyi.system.service.ICCustomerLabelService;
import com.ruoyi.system.service.ICrmUserService;
import com.ruoyi.system.service.ICrmJobService;
import com.ruoyi.util.BirthdayUtil;
import com.ruoyi.util.FirstLetterUtil;
import com.ruoyi.util.PhoneModel;
import com.ruoyi.util.PhoneNumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/crmCustomer")
public class CrmUserController extends BaseController {
    @Autowired
    private ICrmUserService crmCustomerServiceImpl;
    @Autowired
    private ICrmJobService crmJobServiceImpl;
    @Autowired
    private ICCustomerLabelService customerLabelService;

    /**
     * 客户列表 根据城市查看客户情况 地图使用
     * @param
     * @return
     */
    @GetMapping("/selectCrmCustomerListByMap")
    public AjaxResult selectCrmCustomerList(String cusName,String cityCode){
        AjaxResult ajax = AjaxResult.success();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId=loginUser.getUser().getUserId();
        CrmUser crmCustomer =new CrmUser();
        crmCustomer.setCusCityCode(cityCode);
        if(StringUtils.isNotEmpty(cusName))
        crmCustomer.setTitle(cusName);
        crmCustomer.setCreateUser(userId);
        LitterBsCityDTO crmCustomers = crmCustomerServiceImpl.selectCrmCustomerListByMap(crmCustomer,null);
        ajax.put("data",crmCustomers);
        return ajax;
    }
    /**
     * 客户列表
     * @param
     * @return
     */
    @GetMapping("/selectCrmCustomerList")
    public AjaxResult selectCrmCustomerList(String cusName,Long groupId,String label,String cityCode,
                                            @RequestParam(value = "orderByColumn",defaultValue = "cus_user_initals") String orderByColumn,
                                            @RequestParam(value = "isAsc",defaultValue = "asc") String isAsc
                                            ){
        AjaxResult ajax = AjaxResult.success();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId=loginUser.getUser().getUserId();
        CrmUser crmCustomer =new CrmUser();
        crmCustomer.setCusGroupId(groupId);
        crmCustomer.setCusCityCode(cityCode);
        crmCustomer.setTitle(cusName);
        crmCustomer.setCreateUser(userId);
        startPage();
        List<CrmUser> crmCustomers = crmCustomerServiceImpl.selectCrmCustomerListNew(crmCustomer,cusName);
        ajax.put("data",getDataTable(crmCustomers));
        return ajax;
    }

    /**
     * 根据标签查询客户列表
     * @param
     * @return
     */
    @GetMapping("/selectCrmCustomerListByLabel")
    public AjaxResult selectCrmCustomerListByLable(String labelName){
        AjaxResult ajax = AjaxResult.success();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId=loginUser.getUser().getUserId();
        startPage();
        List<CCustomerLabel> list=customerLabelService.selectCCustomerLabelListByLabel( labelName, userId);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        //rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        List<Long> labelListLong = list.stream().map(s -> s.getCusId()).collect(Collectors.toList());
        List<CrmUser> crmCustomers = crmCustomerServiceImpl.selectCrmCustomerListByIds(labelListLong);
        rspData.setRows(crmCustomers);
        ajax.put("data",rspData);
        return ajax;
    }
    /**
     * 按照跟进时间来查看几天内跟进的客户列表情况
     * @param
     * @return
     */
    @GetMapping("/selectCrmCustomerListByTime")
    public AjaxResult selectCrmCustomerListByTime(String startTime,String endTime){
        AjaxResult ajax = AjaxResult.success();
        Long userId=SecurityUtils.getUserId();
        startPage();
        List<CrmUser> crmCustomers = crmCustomerServiceImpl.selectCrmUserListByTime(DateUtils.parseDate(startTime),DateUtils.parseDate(endTime),userId);
        ajax.put("data",getDataTable(crmCustomers));
        return ajax;
    }
    /**
     * 按照跟进时间来查看n天内未跟进的客户列表情况
     * @param
     * @return
     */
    @GetMapping("/selectCrmCustomerListByNoTime")
    public AjaxResult selectCrmCustomerListByNoTime(String startTime,String endTime){
        AjaxResult ajax = AjaxResult.success();
        Long userId=SecurityUtils.getUserId();
        startPage();
        List<CrmUser> crmCustomers = crmCustomerServiceImpl.selectCrmUserListByNoTime(DateUtils.parseDate(startTime),DateUtils.parseDate(endTime),userId);
         ajax.put("data",getDataTable(crmCustomers));
        return ajax;
    }
    /**
     * 查看n天内的生日客户倒序 未来
     * @param
     * @return
     */

    /**
     * 查看未来几天内过生日的人
     * @param day 天数
     * @return
     */
    @GetMapping("/selectCrmUserListByBirthDayByDay")
    public AjaxResult selectCrmUserListByBirthDayByDay(Integer day){
        AjaxResult ajax = AjaxResult.success();
        Long userId=SecurityUtils.getUserId();
        startPage();
        List<CrmUser> crmCustomers = crmCustomerServiceImpl.selectCrmUserListByBirthDayByDay(day,userId);
        ajax.put("data",getDataTable(crmCustomers));
        return ajax;
    }

    /**
     *查看周期内过生日的人
     * @param type type=1代表今天 2代表本周 3代表下周4代表本月5代表下月
      * @return
     */
    @GetMapping("/selectCrmUserListByBirthDayType")
    public AjaxResult selectCrmUserListByBirthDay(Integer type){
        AjaxResult ajax = AjaxResult.success();
        Long userId=SecurityUtils.getUserId();
        startPage();
        List<CrmUser> crmCustomers = crmCustomerServiceImpl.selectCrmUserListByBirthDay(type,userId);
        ajax.put("data",getDataTable(crmCustomers));
        return ajax;
    }

    /**
     * 添加客户
     * @param crmCustomer
     * @return
     */
    @PostMapping("/insertCrmCustomer")
    public AjaxResult insertCrmCustomer(@RequestBody CrmUser crmCustomer){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId=loginUser.getUser().getUserId();
        if(StringUtils.isEmpty(crmCustomer.getCusName())){
           return AjaxResult.error("未填写姓名");
        }
        if(StringUtils.isEmpty(crmCustomer.getCusPhone())){
            return AjaxResult.error("未填写手机号");
        }
        CrmUser crmCustomerOld =new CrmUser();
        crmCustomerOld.setCusPhone(crmCustomer.getCusPhone());
        List<CrmUser> crmUserList=crmCustomerServiceImpl.selectCrmCustomerList(crmCustomerOld);
        if(crmUserList!=null && crmUserList.size()>0){
            return AjaxResult.error("手机号已存在");
        }
        if(FirstLetterUtil.isChinese(crmCustomer.getCusName())){
            crmCustomer.setCusUserInitals(FirstLetterUtil.getFirstLetter(crmCustomer.getCusName()));
        }else{
            String yis = crmCustomer.getCusName().substring(0, 1);
            //输出结果并且把获取到的字母转换成大写
            System.out.println(yis.toUpperCase());
            crmCustomer.setCusUserInitals(yis.toUpperCase());
        }
        if(StringUtils.isEmpty(crmCustomer.getCusAvatarUrl()) || crmCustomer.getCusAvatarUrl().equals("../../static/user_img/avatar_img.png")){
            crmCustomer.setCusAvatarUrl("https://jsqz-crm-upload.oss-cn-beijing.aliyuncs.com/avatar_img.png");
        }
        return crmCustomerServiceImpl.insertCrmCustomer(crmCustomer,userId) > 0 ? AjaxResult.success("添加成功"): AjaxResult.error("添加失败");
    }

    /**
     * 批量添加客户
     * @param manyCrmUser
     * @return
     */
    @PostMapping("/batchInsertCrmCustomer")
    public AjaxResult batchInsertCrmCustomer(@RequestBody ManyCrmUser manyCrmUser){

        Gson gson=new Gson();
        System.out.println("manyCrmUser>>"+gson.toJson(manyCrmUser));
        Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
        if(manyCrmUser==null || manyCrmUser.getCrmCustomerList()==null || manyCrmUser.getCrmCustomerList().size()==0){
            return AjaxResult.error("导入数据不能为空");
        }
        //TODO判断是否有重复手机号，有重复跳过
        CrmUser crmCustomer =new CrmUser();
        crmCustomer.setCreateUser(userId);
        List<CrmUser> crmCustomers = crmCustomerServiceImpl.selectCrmCustomerList(crmCustomer);
        Date date=new Date();
        /*List<CrmUser> crmUserList=new ArrayList<CrmUser>();
        for(CrmUser crmUser:manyCrmUser.getCrmCustomerList()){
            crmUser.setCreateUser(userId);
            crmUser.setCreateTime(date);
            crmUser.setCusAvatarUrl("https://jsqz-crm-upload.oss-cn-beijing.aliyuncs.com/avatar_img.png");

         }*/
        // 差集 (list1 - list2)
        List<CrmUser> listadd =
                manyCrmUser.getCrmCustomerList().stream().filter(item -> !crmCustomers.stream().map(up -> up.getCusPhone()).collect(
                        Collectors.toList()).contains(item.getCusPhone())).collect(Collectors.toList());
        if(listadd==null || listadd.size()==0){
            return AjaxResult.error("导入联系人信息都已存在");
        }
        long startnwo=System.currentTimeMillis();

        for(CrmUser crmUser:listadd){
            crmUser.setCreateUser(userId);
            crmUser.setCreateTime(date);
            crmUser.setCusAvatarUrl("https://jsqz-crm-upload.oss-cn-beijing.aliyuncs.com/avatar_img.png");
            if(StringUtils.isNotEmpty(crmCustomer.getCusName())){
                if(FirstLetterUtil.isChinese(crmCustomer.getCusName())){
                    crmCustomer.setCusUserInitals(FirstLetterUtil.getFirstLetter(crmCustomer.getCusName()));
                }else{
                    String yis = crmCustomer.getCusName().substring(0, 1);
                    //输出结果并且把获取到的字母转换成大写
                    System.out.println(yis.toUpperCase());
                    crmCustomer.setCusUserInitals(yis.toUpperCase());
                }
            }
            //看看是否能获取到经纬度信息
            long starttime=System.currentTimeMillis();
            if(crmUser.getCusPhone()!=null){
                //String cusPhone=crmUser.getCusPhone();
                //将手机号过滤为手机号
                String cusPhone=PhoneNumberUtil.replaceSpaceStr2(crmUser.getCusPhone());
                if(StringUtils.isNotEmpty(cusPhone)){
                    PhoneModel phoneModel = PhoneNumberUtil.getPhoneModel(cusPhone);
                    if (null != phoneModel) {   //可能会有空的情况
                        System.out.println(phoneModel.getProvinceName() + "     " + phoneModel.getCityName());
                        crmUser.setCusAreaCode(phoneModel.getProvinceName());
                        crmUser.setCusCityCode(phoneModel.getProvinceName());
                        crmUser.setCusProvinceCode(phoneModel.getProvinceName());
                    }
                }

            }
            long end=System.currentTimeMillis();
            System.out.println("end-start=="+(end-starttime));
         }
        long endmow=System.currentTimeMillis();
        System.out.println("endm=====ow="+(endmow-startnwo));
        return crmCustomerServiceImpl.batchInsertCrmCustomer(listadd) > 0 ? AjaxResult.success("添加成功"): AjaxResult.error("添加失败");
    }


    /**
     * 获取某人介绍的人列表
     * @param crmCustomerId
     * @return
     */
    @GetMapping("/getCustomerListByResource")
    public AjaxResult getCustomerListByResource(Long crmCustomerId){
        AjaxResult ajax= AjaxResult.success();
        if(crmCustomerId == null || crmCustomerId.longValue() == 0l){
            return AjaxResult.error("无客户id");
        }
        CrmUser crmCustomer =new CrmUser();
        crmCustomer.setCusResources(crmCustomerId);
        List<CrmUser> results = crmCustomerServiceImpl.selectCrmCustomerList(crmCustomer);
        ajax.put("data",results);
        return ajax;
    }

    /**
     * 获取客户详情
     * @param crmCustomerId
     * @return
     */
    @GetMapping("/getCrmCustomerDetile")
    public AjaxResult getCrmCustomerDetile(Long crmCustomerId){
        AjaxResult ajax = AjaxResult.success();
        if(crmCustomerId == null || crmCustomerId.longValue() == 0l){
            return AjaxResult.error("无客户id");
        }
        CrmUser result = crmCustomerServiceImpl.selectCrmCustomerById(crmCustomerId);
        if(result.getCusBirthday()!=null){
            Integer age=BirthdayUtil.getAge(result.getCusBirthday());
            result.setAge(age);
            String chineseZodiac=BirthdayUtil.getChineseZodiac(result.getCusBirthday());
            result.setChineseZodiac(chineseZodiac);
            String constellation=BirthdayUtil.getConstellation(result.getCusBirthday());
            result.setConstellation(constellation);
        }
        if(result.getCusResources()!=null) {
            CrmUser resouces = crmCustomerServiceImpl.selectCrmCustomerById(result.getCusResources());
            result.setCusResourcesUser(resouces);
        }
        ajax.put("data",result);
        return ajax;
    }

    /**
     * 获取客户相关的任务
     * @param crmCustomerId
     * @return
     */
    @GetMapping("/getCustomerJob")
    public AjaxResult getCustomerJob(Long crmCustomerId){
        AjaxResult ajax= AjaxResult.success();
        if(crmCustomerId == null || crmCustomerId.longValue() == 0l){
            return AjaxResult.error("无客户id");
        }
        List<CrmJob> jobByCustomer = crmJobServiceImpl.getJobByCustomer(crmCustomerId);
        ajax.put("data",jobByCustomer);
        return ajax;
    }



    /**
     * 删除客户  同时移除有关联的事件
     * @param crmCustomerId
     * @return
     */
    @GetMapping("/deleteCustomer")
    public AjaxResult deleteCustomer(Long crmCustomerId){
        //校验当前用户是否可以删除客户
        if(crmCustomerId == null || crmCustomerId.longValue() == 0l){
            return AjaxResult.error("无客户id");
        }
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Integer integer = crmCustomerServiceImpl.deleteCustomerAndJob(crmCustomerId, userId);
        return integer > 0? AjaxResult.success("删除成功"): AjaxResult.error("删除失败");
    }

    /**
     * 最近联系的用户
     * @return
     */
    @GetMapping("/recentlyLinkedCustomer")
    public AjaxResult recentlyLinkedCustomer(){
        AjaxResult ajax=AjaxResult.success();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<CrmUser> crmCustomers = crmCustomerServiceImpl.recentlyLinkedCustomer(loginUser.getUser().getUserId());
        ajax.put("data",crmCustomers);
        return ajax;
    }



    @PostMapping("/updateCustomer")
    public AjaxResult updateCustomer(@RequestBody CrmUser crmCustomer){
        if(StringUtils.isEmpty(crmCustomer.getCusName())){
            return AjaxResult.error("未填写姓名");
        }
        if(StringUtils.isEmpty(crmCustomer.getCusPhone())){
            return AjaxResult.error("未填写手机号");
        }
        int i = crmCustomerServiceImpl.updateCrmCustomer(crmCustomer);
        return i > 0 ? AjaxResult.success("修改成功"): AjaxResult.error("修改失败");
    }

    /**
     * 获取附近的客户
     * @param lgla
     * @return
     */
    @GetMapping("/getNearCustomer")
    public AjaxResult getNearCustomer(String lgla,
                                      @RequestParam(value="distance",defaultValue = "10000",required = false) Integer distance ){
        if(StringUtils.isEmpty(lgla) || !lgla.contains(",")){
            return AjaxResult.error("坐标无效");
        }
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();

        AjaxResult ajax=AjaxResult.success();
        List<CrmUser> nearCrmCustomer = crmCustomerServiceImpl.getNearCrmCustomerByLgLa(userId,lgla,distance);
        ajax.put("data",nearCrmCustomer);
        return ajax;
    }
}



